<template>
  <page-wrap>
    <search-wrap
      :schema="searchSchema"
      @reset="setSearchParams"
      @search="setSearchParams"
    />
    <div class="mb-10px">
      <a-button type="primary" @click="addAction">新增</a-button>
    </div>
    <table-wrap
      :columns="tableColumns"
      :data="dataList"
      :pagination="pagination"
      :loading="loading"
      @register="tableRegister"
    />
  </page-wrap>

  <a-drawer
    :width="600"
    :visible="addDrawerVisible"
    :unmount-on-close="true"
    @cancel="addDrawerVisible = false"
  >
    <template #title>新增</template>
    <AddForm ref="addFormRef" />
    <template #footer>
      <a-button @click="addDrawerVisible = false">关闭</a-button>
      <a-button type="primary" :loading="saveLoading" @click="save">
        保存
      </a-button>
    </template>
  </a-drawer>

  <a-drawer
    :width="600"
    :visible="editDrawerVisible"
    :unmount-on-close="true"
    @cancel="editDrawerVisible = false"
  >
    <template #title>编辑</template>
    <EditForm ref="editFormRef" :current-id="currentId" />
    <template #footer>
      <a-button @click="editDrawerVisible = false">关闭</a-button>
      <a-button type="primary" :loading="saveLoading" @click="update">
        保存
      </a-button>
    </template>
  </a-drawer>
</template>
<script setup lang="tsx">
  import { Link } from '@arco-design/web-vue';

  import {
    listApi,
    saveApi,
    updateApi,
    removeApi,
  } from '@/api/tenant/tenant-info';
  import type { TenantInfoVO } from '@/api/tenant/tenant-info/types';
  import { useTable } from '@/hooks/table';

  import AddForm from './components/add-form.vue';
  import EditForm from './components/edit-form.vue';

  const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
      const { pageParams } = tableState;
      return await listApi({
        ...pageParams.value,
        ...unref(searchParams),
      });
    },
    fetchDelApi: async () => {
      const res = await removeApi(unref(currentId));
      return !!res;
    },
  });

  const { dataList, loading, pagination } = tableState;
  const { getList, delList } = tableMethods;

  const tableColumns = reactive<TableColumn[]>([
    {
      field: 'index',
      title: '序号',
      type: 'index',
    },
    {
      field: 'code',
      title: '编码',
    },
    {
      field: 'name',
      title: '名称',
    },
    {
      field: 'domain',
      title: '域名',
    },
    {
      field: 'state',
      title: '启用状态',
      type: 'enumTag',
      enumName: 'State',
    },
    {
      field: 'action',
      title: '操作',
      width: 200,
      render: (data: any) => {
        const row = data.record as TenantInfoVO;
        return (
          <>
            <Link onClick={() => editAction(row.id)}>编辑</Link>
            <Link onClick={() => delAction(row.id)}>删除</Link>
          </>
        );
      },
    },
  ]);

  const searchSchema = reactive<FormSchema[]>([
    {
      field: 'code',
      label: '编码',
      type: 'Input',
    },
    {
      field: 'name',
      label: '名称',
      type: 'Input',
    },
    {
      field: 'domain',
      label: '域名',
      type: 'Input',
    },
    {
      field: 'state',
      label: '启用状态',
      type: 'Select',
      enumName: 'State',
    },
  ]);

  const searchParams = ref({});

  const setSearchParams = (data: any) => {
    searchParams.value = data;
    getList(false);
  };

  const currentId = ref<string>();

  const addDrawerVisible = ref(false);
  const editDrawerVisible = ref(false);

  const addFormRef = ref<ComponentRef<typeof AddForm>>();
  const editFormRef = ref<ComponentRef<typeof EditForm>>();

  const saveLoading = ref(false);

  const addAction = () => {
    currentId.value = undefined;
    addDrawerVisible.value = true;
  };

  const save = async () => {
    const addForm = unref(addFormRef);
    const formData = await addForm?.submit();
    if (formData) {
      saveLoading.value = true;
      let result = false;
      try {
        const res = await saveApi(formData as TenantInfoVO);
        result = !!res;
        if (result) {
          getList(false);
          addDrawerVisible.value = false;
        }
      } catch (error) {
        console.log(error);
      } finally {
        saveLoading.value = false;
      }
    }
  };

  const editAction = (id: string) => {
    currentId.value = id;
    editDrawerVisible.value = true;
  };

  const update = async () => {
    const editForm = unref(editFormRef);
    const formData = await editForm?.submit();
    if (formData) {
      saveLoading.value = true;
      let result = false;
      try {
        const res = await updateApi(formData as TenantInfoVO);
        result = !!res;
        if (result) {
          getList();
          editDrawerVisible.value = false;
        }
      } catch (error) {
        console.log(error);
      } finally {
        saveLoading.value = false;
      }
    }
  };

  const delAction = async (id: string) => {
    currentId.value = id;
    await delList(1);
  };
</script>
